package com.xiaoye.qbproject.controller.qbzyk;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaoye.qbproject.controller.base.BaseController;
import com.xiaoye.qbproject.domain.AjaxResult;
import com.xiaoye.qbproject.domain.QbWarfare;
import com.xiaoye.qbproject.page.TableDataInfo;
import com.xiaoye.qbproject.service.QbWarfareService;
import com.xiaoye.qbproject.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : ChenYao
 * @version : 1.0
 * @description : 战争
 * @create : 2024-12-30 14:46
 */
@RestController
@RequestMapping("/qbWarfare")
public class QbWarfareController extends BaseController {
    @Autowired
    private QbWarfareService qbWarfareService;

    @GetMapping("list")
    public TableDataInfo list(QbWarfare qbWarfare) {
        startPage();
        // areaId和name都支持模糊/精确查询
        List<QbWarfare> list = qbWarfareService.selectListWithAreaName(qbWarfare);
        return getDataTable(list);
    }

    @GetMapping("/dropDown")
    public AjaxResult dropDown() {
        List<QbWarfare> list = qbWarfareService.list();
        return success(list);
    }

    @GetMapping("{id}")
    public AjaxResult get(@PathVariable String id) {
        QbWarfare qbWarfare = qbWarfareService.getById(id);
        return success(qbWarfare);
    }

    @PostMapping
    public AjaxResult save(@RequestBody QbWarfare qbWarfare) {
        return toAjax(qbWarfareService.save(qbWarfare));
    }

    @PutMapping
    public AjaxResult update(@RequestBody QbWarfare qbWarfare) {
        return toAjax(qbWarfareService.updateById(qbWarfare));
    }

    @DeleteMapping("{id}")
    public AjaxResult delete(@PathVariable String id) {
        return toAjax(qbWarfareService.removeById(id));
    }

    /**
     * 二级树接口，areaName为一级，战争name为二级
     */
    @GetMapping("/tree")
    public AjaxResult tree() {
        // 自定义优先级字段（可扩展）
        List<String> priorityLabels = Arrays.asList("俄乌战争","叙利亚战争","第二次纳卡战争","巴以冲突","缅甸政变","也门内战","阿富汗战争","印巴战争");

        // 构建优先级索引映射（提升查找效率）
        Map<String, Integer> priorityIndexMap = new HashMap<>();
        for (int i = 0; i < priorityLabels.size(); i++) {
            priorityIndexMap.put(priorityLabels.get(i), i);
        }
        // 查询所有战争，带areaName
        List<QbWarfare> list = qbWarfareService.selectListWithAreaName(new QbWarfare());
        // 按areaName分组，null用'未知区域'代替
        Map<String, List<QbWarfare>> areaMap = list.stream().collect(Collectors.groupingBy(w -> w.getAreaName() == null ? "未知区域" : w.getAreaName()));
        // 组装树结构
        List<Map<String, Object>> tree = new ArrayList<>();
        for (Map.Entry<String, List<QbWarfare>> entry : areaMap.entrySet()) {
            Map<String, Object> areaNode = new HashMap<>();
            areaNode.put("label", entry.getKey());
            List<Map<String, Object>> children = entry.getValue().stream().map(w -> {
                Map<String, Object> child = new HashMap<>();
                child.put("id", w.getId());
                child.put("label", w.getName());
                return child;
            }).collect(Collectors.toList());
            children.sort((node1, node2) -> {
                String label1 = (String) node1.get("label");
                String label2 = (String) node2.get("label");

                // 获取优先级索引
                Integer index1 = priorityIndexMap.get(label1);
                Integer index2 = priorityIndexMap.get(label2);

                // 1. 优先级标签排序
                if (index1 != null && index2 != null) {
                    return Integer.compare(index1, index2);
                }
                // 2. 只有一个是优先级标签
                if (index1 != null) {
                    return -1;
                }
                if (index2 != null) {
                    return 1;
                }

                // 3. 非优先级标签按自然顺序排序
                return label1.compareTo(label2);
            });
            areaNode.put("children", children);
            tree.add(areaNode);
        }

        tree.sort((node1, node2) -> {
            String label1 = (String) node1.get("label");
            String label2 = (String) node2.get("label");
            return label1.compareTo(label2);
        });

        return success(tree);
    }
}
